import requests
import random
import time
import logging

initCookie = '_boogle_session=z70gJb2%2FKcGCoXXteMCzZyF76%2FVpJ1WD6zRQ9vgSMtmVTRaimYAGOFUj4QGp6onk%2BceJTPOLHDBZW8m2bd7yO0i4ETIWs%2FOvYm58fSNUEzaVTXnatLFBH2W2UKkd%2FdYOfIOpPzD239g27I%2BByJMhtGGnQVczQlGByWoTSJXaXUsQNMVDsjByq2IhjLhO9flOF24%2BsJzBKb1r3VpGb8Egto0ozrFKCMCtTysliJ9L665scYLk6yXmW1vYqbJwIWxBpfePAUqnphx%2F60eiiRmZOdYMRvwvFWSFJDy6uyn00DsjCk5Y8b4k%2BymKvERh%2BrgjWN%2BxGe49mJ4FHAxyjRsBKh8pBq4ez08QU6CujrignPT8xLdGyV4ejvODNNnI3jBTPpbz7s%2BGkksWvAO49YIiQA4%2BJfB4ASRFiH6bjNda9rsRLunkUygAXDekW5DjIQ%3D%3D--Ki6yovlGqkcg15Cy--sU%2BmUwNvFr89%2BDHBz0DF%2Bw%3D%3D'
count = 0
version = 'apple '
exCnt = 0


def genKeyWord():
    global count
    global version

    count = count + 1
    rcnt = random.randint(1, 5)
    word = ''
    for i in range(rcnt):
        word = word + chr(random.randint(65, 90))

    word = word + ' ' + version + ' ' + str(count) + ' '

    rcnt = random.randint(1, 5)
    for i in range(rcnt):
        word = word + chr(random.randint(65, 90))

    return word


def doSearch(keyWord):
    global initCookie
    global exCnt
    global count

    hs = {
        'Host': 'boogle.io',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'https://boogle.io/',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cookie': initCookie
    }

    latp = str(random.randint(0, 1000000000))
    lngp = str(random.randint(0, 1000000000))
    url = 'https://boogle.io/api/v1/get_search_result?q=' + keyWord + '&location=22.' + latp + ',114.' + lngp + '&identifier=1&source=false '
    rsp = requests.get(url, headers=hs)
    if rsp.status_code != 200 or rsp.headers['Set-Cookie'] == '':
        exCnt = exCnt + 1
    else:
        exCnt = 0
        print('------------', count)
        logging.info('------------' + bytes(count))

    if exCnt > 10:
        print('!!! NEED RELOGIN', rsp.status_code, rsp.headers['Set-Cookie'])
        logging.error('------------', '!!! NEED RELOGIN' + bytes(rsp.status_code) + rsp.headers['Set-Cookie'])


if __name__ == '__main__':
    logging.basicConfig(filename="t_alert.log", filemode="a", format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
                        datefmt="%d-%m-%Y %H:%M:%S", level=logging.DEBUG)
    while True:
        try:
            keyWord = genKeyWord()
            doSearch(keyWord)
            time.sleep(0)
        except Exception as e:
            print(e)
